package edu.zju.gis.dbfg.common.base;

import edu.zju.gis.dbfg.common.Page;
import edu.zju.gis.dbfg.common.Result;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Hu
 * 实现Controller的基础CURD方法
 * @date 2019/4/29
 **/
public abstract class BaseController<T extends BaseEntity, Service extends BaseService, ID extends Serializable, Search extends BaseFilter> {

  /**
   * 注入Service
   */
  @Autowired
  public Service service;

  /**
   * 获取已经分页的数据结果
   * 默认pageNo=1, pageSize=20
   * @param param
   * @param page
   * @return
   */
  @RequestMapping(value = "/page", method = RequestMethod.POST)
  @ResponseBody
  public Result getPage(@RequestBody Search param, Page page) {
    return Result.success().setBody(service.search(param, page));
  }

  /**
   * 删除对象
   * @param id
   * @return
   */
  @RequestMapping(value = "/delete", method = RequestMethod.GET)
  @ResponseBody
  public Result delete(@RequestParam("id") ID id) {
    return Result.success().setBody(service.delete(id));
  }

  /**
   * 批量删除对象
   * @param batch
   * @return
   */
  @RequestMapping(value = "/delete", method = RequestMethod.POST)
  @ResponseBody
  public Result deleteBatch(@RequestBody JSONObject batch) {
    List<ID> ts = new ArrayList<>();
    for(String id:Arrays.asList(batch.getString("ids").split(","))){
      ts.add((ID)id);
    }
    return Result.success().setBody(service.delete(ts));
  }

  /**
   * 获取实例
   * @param id
   * @return
   */
  @RequestMapping(value = "", method = RequestMethod.GET)
  @ResponseBody
  public Result get(@RequestParam("id") ID id) {
    return Result.success().setBody(service.select(id));
  }

  /**
   * 更新实例
   * @param t
   * @return
   */
  @RequestMapping(value = "", method = RequestMethod.PUT)
  @ResponseBody
  public Result update(@RequestBody T t) {
    return Result.success().setBody(service.update(t));
  }

  /**
   * 新增实例
   * @param t
   * @return
   */
  @RequestMapping(value="", method = RequestMethod.POST)
  @ResponseBody
  public Result create(@RequestBody T t){
    return Result.success().setBody(service.save(t));
  }

}
